package com.hou.selector;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

//消费者
public class Consumer {

    public static void main(String[] args) throws JMSException {
        ConnectionFactory factory = new ActiveMQConnectionFactory(
                "houzheng",//默认的用户
                "houzheng",
                "tcp://localhost:61616"  //默认端口: 61616
        );
        Connection connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
        Destination destination=session.createQueue("myqueue");//必须和生产者指定的queue一样
        //使用消息消息选择器,只看name=侯征的,  选择器语法由SQL92语法定义
        //注意: 日期和时间需要使用标准的long型毫秒值,
        MessageConsumer consumer = session.createConsumer(destination,"name ='姚振' and money > 500");
        //接受消息
        while(true){
            //可以为消费者消息监听器来接受,监听接受消息是异步接受,receive是同步接受的
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    //接受消息之后的处理
                }
            });
            TextMessage message = (TextMessage) consumer.receive();//阻塞接受,还可以指定等待时间或者不阻塞接受,没有就跳过

            if(message==null)break;
            System.out.println(message.getStringProperty("name"));
            System.out.println(message.getDoubleProperty("money"));
            System.out.println("--------------");
        }
        if(connection!=null)connection.close();//关闭连接
    }
}
